<?php
/**
 * Creater: 李青林
 * Date Time : 2018/8/22 19:15
 */

namespace App\Http\Models;


class StatisticsUserVoucher extends BaseModel
{
    protected $table = 'statistics_user_voucher';
    protected $guarded = [];

    /**
     * @param $userId 用户id
     * @param $number 点劵数量
     * @param $type 类型,1商品退回 ,0 发布商品消费
     * @param $goods_id 商品id
     * @return mixed
     */
    public static function updateUserVoucher($userId, $number, $type, $goods_id)
    {
        $goods_info = Goods::where(['id' => $goods_id])->first();//find();
        $model = self::where(['user_id' => $userId])->first();
        if (empty($model)) {
            self::create(['user_id' => $userId, 'day_voucher' => 0, 'months_voucher' => 0]);
            $model = self::where(['user_id' => $userId])->first();
        }
        if ($type !== 2 && $goods_id != 0) {
            if (date('Y-m-d', strtotime($goods_info->created_at)) == date('Y-m-d', time())) {
                if ($type == 0) {
                    $model->increment('day_voucher', $number);
                    $model->increment('months_voucher', $number);
                } elseif ($type == 1) {
                    if ($model->day_voucher - $number < 0) {
                        $model->day_voucher = 0;
                    } else {
                        $model->decrement('day_voucher', $number);
                    }
                    if ($model->months_voucher - $number < 0) {
                        $model->months_voucher = 0;
                    } else {
                        $model->decrement('months_voucher', $number);
                    }
                }
                return $model->save();
            }
        }
        return true;
    }
}